//
//  WLWebController.m
//  WangliBank
//
//  Created by 王启镰 on 16/6/21.
//  Copyright © 2016年 iSoftstone infomation Technology (Group) Co.,Ltd. All rights reserved.
//

#import "WYWebController.h"
#import "WYWebProgressLayer.h"
#import "UIView+Frame.h"
#import "WLWebProgressLayer.h"

@interface WYWebController ()<UIWebViewDelegate>

@end

@implementation WYWebController
{
    UIWebView *_webView;
    
    WYWebProgressLayer *_progressLayer; ///< 网页加载进度条
}
+ (WYWebController*) webControllerWithURL:(NSString*) url
{
    WYWebController *controller = [[[self class] alloc] init];
    controller.url = url;
    return controller;
}
+ (WYWebController*) webControllerWithTitle:(NSString*) title content:(NSString*) content
{
    WYWebController *controller = [[[self class] alloc] init];
    controller.titleStr = title;
    controller.content = [self getHtmlData:content];
    return controller;
}

+ (NSString*) getHtmlData:(NSString*) content{
    if(kStringIsEmpty(content))
        return @"";
    NSMutableString *str = [[NSMutableString alloc] init];
    [str appendString:@"<html>"];
    [str appendString:@"<head>"];
    [str appendString:@"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">"];
    [str appendString:@"<style>img{max-width: 100%; width:auto; height:auto;}</style>"];
    [str appendString:@"</head>"];
    [str appendString:@"<body>"];
    [str appendString:content];
    [str appendString:@"</body></html>"];
    return str;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
}

- (void)setupUI {
    _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    _webView.delegate = self;
    if(!kStringIsEmpty(self.url)){
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
        [_webView loadRequest:request];
    }else{
        [_webView loadHTMLString:self.content baseURL:nil];
    }
    _webView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_webView];
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    _progressLayer = [WYWebProgressLayer layerWithFrame:CGRectMake(0, -1, [UIScreen mainScreen].bounds.size.width, 2)];
    [self.view.layer addSublayer:_progressLayer];
    [_progressLayer startLoad];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [_progressLayer finishedLoad];
    if(self.url){
        self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }else{
        self.title = self.titleStr;
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [_progressLayer finishedLoad];
}

- (void)dealloc {
    NSLog(@"i am dealloc");
}

@end
